package com.sansan.ultrasound_handpad.fragment.home;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.Process;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.view.LayoutInflaterCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.qmuiteam.qmui.layout.QMUIFrameLayout;
import com.qmuiteam.qmui.skin.QMUISkinHelper;
import com.qmuiteam.qmui.skin.QMUISkinLayoutInflaterFactory;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.QMUICollapsingTopBarLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.popup.QMUIFullScreenPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.sansan.ultrasound_handpad.R;
import com.sansan.ultrasound_handpad.activity.MainActivity;
import com.sansan.ultrasound_handpad.adaptor.brvah.PcbTaskPositionRecordAdapter;
import com.sansan.ultrasound_handpad.base.BaseFragment;
import com.sansan.ultrasound_handpad.base.MmkvManager;
import com.sansan.ultrasound_handpad.convertor.JsonConverter;
import com.sansan.ultrasound_handpad.entity.DeviceProductReplaceElementEntity;
import com.sansan.ultrasound_handpad.entity.PcbScanProductResult;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecord;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecordDetail;
import com.sansan.ultrasound_handpad.entity.PcbTaskPositionRecordDetailEntity;
import com.sansan.ultrasound_handpad.entity.StaffEntity;
import com.sansan.ultrasound_handpad.manager.QDPreferenceManager;
import com.yanzhenjie.kalle.JsonBody;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 程序列表数据展示页面
 */
public class LoadFragment extends BaseFragment implements View.OnClickListener {

    private final static String TAG = ProcessFragment.class.getSimpleName();

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private static boolean isAnim = false;

    @BindView(R.id.homefragment_feeding_rButton)
    QMUIRoundButton mFeedingBtn;
    //@BindView(R.id.homefragment_finish_rButton)
    //QMUIRoundButton mFinishBtn;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.collapsing_topbar_layout)
    QMUICollapsingTopBarLayout mCollapsingTopBarLayout;
    @BindView(R.id.topbar)
    QMUITopBar mTopBar;

    LinearLayoutManager mPagerLayoutManager;
    PcbTaskPositionRecordAdapter mAdapter;

    private DeviceProductReplaceElementEntity deviceProductReplaceElementEntity = null;
    private PcbTaskPositionRecordDetailEntity pcbTaskPositionRecordDetailEntity = null;

    private StaffEntity staffEntity = null;
    private Context context = null;
    private String mProductCode = null;
    private String mPcbTaskCode = null;
    private boolean isPopUpShow = false;

    private Timer timer = null;
    private TimerTask timerTask = null;
    private TextView showResult = null;
    private QMUIFullScreenPopup mQmuiFullScreenPopup = null;
    private int statu = 0; // 0:表示上料中 播放上料音频  1:表示上料完成 播放上料完成音频
    private int flag = 2; // flag:表示不同页面的fragment 把fragment拆分之后,flag没有什么作用了 0表示UserFragment 1表示ProcessFragment 2表示LoadFragment
    private int btnStatu = 1; // btnStatu:表示弹框的显示状态 1:表示Gone 0:表示Visibility
    private boolean btnFlag = true; //true表示按钮显示 false表示按钮隐藏 程序列表第一次上料需要点击按钮开始上料
    //private int scanStatu = 1;

    private List<PcbTaskPositionRecordDetail> processList = null;
    private List<DeviceProductReplaceElementEntity> replaceList = null;
    String deviceCode = null;
    String pcbId = null;
    String pcbTaskCode = null;

    private int totalSize;
    private int finishSize;
    //int finishSize = 0;

    private void startTimerTask() {
        stopTimerTask();

        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    scanProductCode(mProductCode, pcbTaskCode, deviceCode);
                }
            };
        }
        timer.schedule(timerTask, 0, 3000L);
    }

    private void stopTimerTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("btnStatu", btnStatu);
        outState.putBoolean("btnFlag", btnFlag);

        Log.d(TAG, "onReceive: onReceiveBtn BtnStatu" + btnStatu);
        Log.d(TAG, "onReceive: onReceiveBtn tnFlag" + btnFlag);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
        if (savedInstanceState != null) {
            String save = savedInstanceState.getString("btnFlag");
            Log.d(TAG, "onCreate: " + save);
        }

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnFlag) {
                    v.setVisibility(View.GONE);
                }
            }
        });


    }


    @Override
    protected View onCreateView() {

        //startFragment(new LoadFragment());
        if (getArguments() != null) {
            staffEntity = (StaffEntity) getArguments().getSerializable("UserMsg");
            processList = (List<PcbTaskPositionRecordDetail>) getArguments().getSerializable("processList");
            deviceCode = (String) getArguments().getSerializable("deviceCode");
            pcbId = (String) getArguments().getSerializable("pcbId");
            pcbTaskCode = (String) getArguments().getSerializable("processTaskCode");
            //replaceList = (List<DeviceProductReplaceElementEntity>) getArguments().getSerializable("replaceList");
        }

        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
        btn.setOnClickListener(this);
        ButterKnife.bind(this, rootView);

        for (PcbTaskPositionRecordDetail detail : processList) {
            if ("2".equals(detail.getInstall_status())) {
                finishSize++;
                Log.d(TAG, "onReceiveBtn: 完成数量" + finishSize);
                btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
                //System.out.println(B);
                if (btnFlag) {
                    btn.setVisibility(View.GONE);
                    Log.d(TAG, "onReceiveBtn: 上料计时中,点击无效 ");
                    btnFlag = false;
                    Log.d(TAG, "onReceiveBtn: btnFlag" + btnFlag);
                    Log.d(TAG, "onReceiveBtn: 遍历后判断完成数量大于0时隐藏 " + btn.getVisibility());
                    Log.d(TAG, "onReceiveBtn: 按钮状态 " + mFeedingBtn.getVisibility());
                }
            }
        }

        if (finishSize != 0) {
            btn.setVisibility(View.GONE);
        }

        //初始化标题布局

        if (mFeedingBtn != null) {
            mFeedingBtn.setVisibility(View.GONE);
        }

        initAdapter();
        mPagerLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mPagerLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        //设置空白布局
        mAdapter.setEmptyView(getScanCodeView());

        mCollapsingTopBarLayout.setScrimUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Log.i(TAG, "scrim: " + animation.getAnimatedValue());
            }
        });

        mCollapsingTopBarLayout.addOnOffsetUpdateListener(new QMUICollapsingTopBarLayout.OnOffsetUpdateListener() {
            @Override
            public void onOffsetChanged(QMUICollapsingTopBarLayout layout, int offset, float expandFraction) {
                Log.i(TAG, "offset = " + offset + "; expandFraction = " + expandFraction);
            }
        });
        return rootView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.homefragment_feeding_rButton:

                startPositonRecord(pcbTaskCode, staffEntity.getUsername(), deviceCode); //todo

                if (btnStatu == 1) {
                    v.setVisibility(View.GONE);
                    btnStatu = 0;
                } else if (btnStatu == 0) {
                    v.setVisibility(View.VISIBLE);
                    Log.d(TAG, "onReceiveBtn: 显示2");
                    //btnStatu = 1;
                } else {
                    v.setVisibility(View.GONE);
                }
                //Toast.makeText(getActivity(), "点击了上料按钮", Toast.LENGTH_SHORT).show();
                //startPositonRecord(pcbTaskCode,staffEntity.getUsername());

                //btn.setVisibility(View.GONE);
                //obtainPcbTaskPostionRecord(deviceCode,pcbId,pcbTaskCode);
            default:
                break;
        }
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        if (mAdapter == null) {
            mAdapter = new PcbTaskPositionRecordAdapter();
            mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    if (view.getId() == R.id.pcb_taskposition_record_rv_item_cb) {
                        Toast.makeText(getActivity(), "勾选了第" + position + "个", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    /**
     * 扫描获取程序信息界面
     */
    private View getScanCodeView() {

        if (mCollapsingTopBarLayout != null) {
            if (staffEntity != null) {
                mCollapsingTopBarLayout.setTitle("欢迎:" + staffEntity.getNickname());
            }
        }

        mTopBar.addLeftTextButton("结束上料", R.id.load_finish_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                //builder.setTitle("退出登录");
                builder.setMessage("确定结束当前程序上料吗?");
                builder.setCancelable(true);
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(getActivity(),"点击了确定！",Toast.LENGTH_SHORT).show();
                                //startFragment(new UserFragment());
                                ProcessFragment loadFragment = new ProcessFragment();
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("UserMsg", staffEntity);
                                loadFragment.setArguments(bundle);
                                startFragment(loadFragment);
                            }
                        });
                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(getActivity(),"点击了取消！",Toast.LENGTH_SHORT).show();
                            }
                        });

                final AlertDialog dlg = builder.create();
                dlg.show();
                //startFragment(new UserFragment());
            }
        });

        View errorView = getLayoutInflater().inflate(R.layout.fragment_home, mRecyclerView, false);
        obtainPcbTaskPostionRecord(deviceCode, pcbId, pcbTaskCode);

        errorView.findViewById(R.id.homefragment_feeding_rButton).setOnClickListener(v -> {
            Toast.makeText(getActivity(), "开始上料", Toast.LENGTH_SHORT).show();
        });

        return errorView;
    }


    /**
     * 从服务器获取程序信息
     */
    public void obtainPcbTaskPostionRecord(String deviceCode, String pcbId, String pcbTaskCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("deviceCode", deviceCode);
            object.put("pcbId", pcbId);
            object.put("processTaskCode", pcbTaskCode);
//            object.put("pcbTaskCode", pcbTaskCode);
//            object.put("deviceCode", "B15002");
//            object.put("pcbId", "DCY2.908.1444GS-RB");
//            object.put("processTaskCode", "WORK014083");
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/buildPositionRecordAndReturn")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<PcbTaskPositionRecord>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbTaskPositionRecord, String> response) {
                        try {
                            Log.d(TAG, "obtainPcbTaskPostionRecord_onResponse: " + response.succeed());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (response.isSucceed()) {
                            if (mAdapter != null) {
                                if (mAdapter.hasEmptyView()) {
                                    mAdapter.removeEmptyView();
                                    //mAdapter.setEmptyView(deviceCode,pcbTaskCode);
                                }
                                PcbTaskPositionRecord record = response.succeed();
                                if (!(response.succeed() instanceof PcbTaskPositionRecord)) {
                                    Log.d(TAG, "onResponse: 不是PcbTaskPositionRecord类型" + response.succeed());
                                    return;
                                }
                                if (record.getDetailList() != null && record.getDetailList().size() > 0) {
                                    if (processList == null) {
                                        processList = new ArrayList<>(response.succeed().getDetailList());
                                    } else {
                                        processList.clear();
                                        processList.addAll(response.succeed().getDetailList());
                                    }
                                    mAdapter.setNewData(processList);
                                    if (mFeedingBtn != null && finishSize == 0) {
                                        mFeedingBtn.setVisibility(View.VISIBLE);
                                        Log.d(TAG, "onReceiveBtn: 显示1");
                                    }
                                    flag = 2; //进入程序列表显示界面
                                    //mProductCode = barcodeStr;
                                    /*启动定时器定时查询*/
                                    //startTimerTask();
                                    startPositonRecord(pcbTaskCode, staffEntity.getNickname(), deviceCode);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 获取IP地址
     */
    private String obtainIP() {
        return MmkvManager.getInstance().getMMKV().decodeString("PAD_IP", "http://192.168.0.192:8756/");
    }

    /**
     * 开始上料
     */
    private void startPositonRecord(String pcbTaskCode, String username, String deviceCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("processTaskCode", pcbTaskCode);
            object.put("username", username);
            object.put("deviceCode", deviceCode);
            Log.d(TAG, "startPositonRecord: " + pcbTaskCode + username);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/startPositonRecord")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        Log.d(TAG, "开始上料: " + response.succeed());

                    }
                });
    }

    /**
     * 扫码广播
     */

    /*接收扫码器传回来的扫码数据*/
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /*扫描数据*/
            byte[] scanData = intent.getByteArrayExtra("barocode");
            /*数据长度*/
            int dataLen = intent.getIntExtra("length", 0);
            /*数据类型*/
            byte dataTyp = intent.getByteExtra("barcodeType", (byte) 0);
            /*条码字符串*/
            String barcodeStr = new String(scanData, 0, dataLen);
            Log.d(TAG, "BroadcastReceiver: " + barcodeStr);

            /**
             * 獲取到工號去查詢
             */
            if (!TextUtils.isEmpty(barcodeStr)) {
                View rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
                Button btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (btnFlag) {
                            v.setVisibility(View.GONE);
                            v.setEnabled(false); //todo
                        }
                    }
                });

                if (btnStatu == 1 && finishSize != 0) {
                    btn.setVisibility(View.GONE);
                    Log.d(TAG, "onReceiveBtn: 完成数量不为0时隐藏 " + btn.getVisibility());
                }

                for (PcbTaskPositionRecordDetail detail : processList) {
                    if ("2".equals(detail.getInstall_status())) {
                        finishSize++;
                        btn = rootView.findViewById(R.id.homefragment_feeding_rButton);
                        if (btnFlag) {
                            btn.setEnabled(false);
                            btnFlag = false;
                            Log.d(TAG, "onReceiveBtn: btnFlag" + btnFlag);
                            Log.d(TAG, "onReceiveBtn: 按钮状态" + btnFlag);
                            btn.setVisibility(View.GONE);
                            Log.d(TAG, "onReceiveBtn: 遍历后判断完成数量大于0时隐藏 " + btn.getVisibility());
                        }

                        Log.d(TAG,"scanTest: processList ___" + processList.iterator().toString());
                        Log.d(TAG,"scanTest: detail ___" + detail.toString());
                    }
                }

                if (btnStatu == 1 && finishSize == 0) {
                    Log.d(TAG, "onReceiveBtn: 完成数量为0时按钮显示状态 " + btn.getVisibility());
                    ToastUtil.showToast(getActivity(), "请点击开始上料按钮再扫码!");
                    return;
                }
                if (showResult != null && (showResult.getVisibility() == View.VISIBLE)) {
                    ToastUtil.showToast(getActivity(), "上料过程中扫码无效!");
                    return;
                }

                if (flag == 2) {
                    mProductCode = barcodeStr;
                    if (barcodeStr.length() == 10 && barcodeStr.startsWith("1010")) {
                        /*启动定时器定时查询*/
                        startTimerTask();
                        scanProductCode(mProductCode, pcbTaskCode, deviceCode);

                    } else {
                        ToastUtil.showToast(getActivity(), "扫描获取的参数异常!");
                        return;
                    }

                }

            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();

        if (getActivity() == null) {
            return;
        }
        /*注册扫描器广播*/
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("urovo.rcv.message");
        getActivity().registerReceiver(this.mScanReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (getActivity() == null) {
            return;
        }
        /*注销扫描器广播*/
        getActivity().unregisterReceiver(this.mScanReceiver);
    }

    private void update(final String productCode, String pcbTaskCode, String deviceCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("productCode", productCode);
            Log.d(TAG, "scanProductCode: test " + productCode);

        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "base/deviceProductReplaceElement/queryByOriginalProductCode")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        Log.d(TAG, "开始上料: " + response.succeed());
                        Log.d(TAG, "scanProductCode: test " + productCode);
                    }
                });
    }


    private void scanProductCode(final String productCode, String pcbTaskCode, String deviceCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("productCode", productCode);
            object.put("processTaskCode", pcbTaskCode);
            object.put("deviceCode", deviceCode);
            Log.d(TAG, "scanProductCode: test " + productCode + " " + pcbTaskCode + " " + deviceCode);

        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/scanProductCode")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
//                .tag(this)
                .perform(new SimpleCallback<PcbScanProductResult>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbScanProductResult, String> response) {
                        Log.d(TAG, "扫描飞达料盘: " + response.succeed());
                        if (response.isSucceed()) {
                            finishSize = 0;
                            PcbTaskPositionRecordDetail param = null;

                            for (PcbTaskPositionRecordDetail detail : processList) {
                                //Log.d(TAG, "scanProductCode: test " + detail);
                                if ("2".equals(detail.getInstall_status())) {
                                    finishSize++;
                                }
                                if (!TextUtils.isEmpty(productCode) && productCode.equals(detail.getProduct_code())) {
                                    param = detail;
                                    continue;
                                }

                                if (!TextUtils.isEmpty(productCode) && productCode.equals(detail.getLast_product_code())) {
                                    param = detail;
                                    continue;
                                }
                                // TODO: 2020/8/18
//                                 多个替代料处理弹出"物料不在程序"的问题  (待考虑)
//                                 目前认为处理的最好方法就是再添加一个字段,将替代料和扫描的物料分开存储,
//                                 一个替代料不存在这个问题 但是多个替代料的话和扫描的物料是不等值的 就会存在报"不存在"的问题
//                                if (!TextUtils.isEmpty(productCode)
//                                        && (detail.getLast_product_code().substring(0,10).equals(productCode)
//                                        || detail.getLast_product_code().substring(11,21).equals(productCode))) {
//                                    param = detail;
//                                    continue;
//                                }
                            }

                            //PcbScanProductResult result = response.succeed();
                            if (!(response.succeed() instanceof PcbScanProductResult)) {
                                Log.d(TAG, "onResponse: 不是PcbScanProductResult类型" + response.succeed());
                                //fullScreenPopupWindow(LoadFragment.this.getView(), null);
                                return;
                            }
                            totalSize = mAdapter.getData().size();
                            if (!isPopUpShow) {
                                if (totalSize <= finishSize) {
                                    finishPositonRecord(pcbTaskCode, deviceCode);
                                    fullScreenPopupWindow(LoadFragment.this.getView(), param);
                                    stopTimerTask();
                                } else if (param != null && "2".equals(param.getInstall_status())) {
                                    if (param.getLast_product_code() != null){
                                        ToastUtil.showToast(getActivity(), "工序" + param.getPosition() + "—— 该物料已插入, " + "\n" + "物料编号为:" + param.getLast_product_code());
                                    } else {
                                        ToastUtil.showToast(getActivity(), "工序" + param.getPosition() + "—— 该物料已插入, " + "\n" + "物料编号为:" + param.getProduct_code());
                                    }
                                    stopTimerTask();
                                    if (param.getLast_product_code()!= null && !param.getProduct_code().equals(param.getLast_product_code()) ){
                                        //todo
                                        AlertDialog.Builder build = new AlertDialog.Builder(getContext());
                                        build.setMessage("请确认是否需要下料?");
                                        build.setCancelable(true);

                                        build.setPositiveButton("是",null);
                                        build.setNegativeButton("否",null);

                                        AlertDialog alertDialog = build.create();
                                        if(!isAnim){
                                            alertDialog.show();
                                            isAnim = true;
                                        } else {
                                            isAnim = false;
                                            return;
                                        }
                                        //isAnim = false;
//                                        AlertDialog alertDialog = build.create();
//                                        alertDialog.show();
                                        Log.d(TAG,"scanProductCode: testing" + "显示弹框");

                                        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                        //Toast.makeText(getActivity(),"点击了确定！",Toast.LENGTH_SHORT).show();
                                                        //startFragment(new UserFragment());
                                                        //dialog.dismiss();
                                                        //dialog.cancel();
                                                        downPositionRecordDetail(productCode);
                                                        final Timer t = new Timer();
                                                        t.schedule(new TimerTask() {
                                                            public void run() {
                                                                LoadFragment loadFragment = new LoadFragment();
                                                                Bundle bundle = new Bundle();
                                                                bundle.putSerializable("UserMsg", staffEntity);
                                                                bundle.putSerializable("processList", (Serializable) processList);
                                                                bundle.putSerializable("deviceCode", deviceCode);
                                                                bundle.putSerializable("pcbId", pcbId);
                                                                bundle.putSerializable("processTaskCode", pcbTaskCode);
                                                                //bundle.putSerializable("replaceList", (Serializable) replaceList);
                                                                loadFragment.setArguments(bundle);
                                                                startFragment(loadFragment);
                                                            }
                                                        }, 1000);
                                                        alertDialog.dismiss();

                                            }
                                        });

                                        alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                alertDialog.dismiss();
                                            }
                                        });


                                    }


                                } else if (param != null && processList.contains(param)) {
                                    Log.d(TAG, "scanProductCode: test " + " " + "______________________");
                                    Log.d(TAG, "scanProductCode: test " + productCode + " " + pcbTaskCode + " " + deviceCode);
                                    fullScreenPopupWindow(LoadFragment.this.getView(), param);
                                    //String last_product_code = param.getLast_product_code();
                                    //↓
                                } else {
                                    Log.d(TAG, "scanProductCode: test " + " " + "______________________");
                                    Log.d(TAG, "scanProductCode: test " + productCode + " " + pcbTaskCode + " " + deviceCode);

                                    //queryByReplaceProductCode(productCode);
                                    //需要一个接口通过上面拿到的物料编号查询这条数据的详细信息,把查询到的detail赋值给param todo
                                    //queryDetailByProductCode(productCode);

                                    fullScreenPopupWindow(LoadFragment.this.getView(), param); //todo
                                    Log.d(TAG, "scanProductCode: test " + param); //下面的代码3
                                }
                            } else if (showResult != null) {
                                if (!(response.succeed() instanceof PcbScanProductResult)) {
                                    Log.d(TAG, "onResponse: 不是PcbScanProductResult类型" + response.succeed());
                                    return;
                                }
                                if (totalSize <= finishSize && param!= null && param.getProduct_code().equals(param.getLast_product_code())) { //todo
                                    showResult.setBackgroundColor(Color.YELLOW);
                                    showResult.setTextSize(70);
                                    showResult.setText("上料结束");
                                    stopTimerTask();
                                    final Timer t = new Timer();
                                    t.schedule(new TimerTask() {
                                        public void run() {
                                            startFragment(new UserFragment());
                                        }
                                    }, 2000);

                                } else if (param == null) {
                                    //fullScreenPopupWindow(LoadFragment.this.getView(), param);
                                    try {
                                        Thread.sleep(100);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    if (mQmuiFullScreenPopup != null) {
                                        mQmuiFullScreenPopup.dismiss();
                                    }
                                    final Timer t = new Timer();
                                    t.schedule(new TimerTask() {
                                        public void run() {
                                            LoadFragment loadFragment = new LoadFragment();
                                            Bundle bundle = new Bundle();
                                            bundle.putSerializable("UserMsg", staffEntity);
                                            bundle.putSerializable("processList", (Serializable) processList);
                                            bundle.putSerializable("deviceCode", deviceCode);
                                            bundle.putSerializable("pcbId", pcbId);
                                            bundle.putSerializable("processTaskCode", pcbTaskCode);
                                            //bundle.putSerializable("replaceList", (Serializable) replaceList);
                                            loadFragment.setArguments(bundle);
                                            startFragment(loadFragment);
                                        }
                                    }, 1000);
                                    fullScreenPopupWindow(LoadFragment.this.getView(), param);
                                } else if ("1".equals(response.succeed().getStatus()) && !param.getInstall_status().equals("2")) {
                                    try {
                                        if (statu == 0) {
                                            mediaPlayer = MediaPlayer.create(getContext(), R.raw.shangliao);
                                            mediaPlayer.start();
                                            statu = 1;
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    showResult.setTextSize(52);
                                    showResult.setText("上料中\n" + param.getPosition());

                                } else if ("2".equals(response.succeed().getStatus())) {
                                    int pos = mAdapter.getData().indexOf(param);
                                    PcbTaskPositionRecordDetail find = mAdapter.getItem(pos);
                                    find.setInstall_status("2");
                                    finishSize++;
                                    Log.d(TAG, "testFinish2: total" + totalSize);
                                    Log.d(TAG, "testFinish2: finish" + finishSize);
                                    mAdapter.notifyDataSetChanged();
                                    try {
                                        if (statu == 1) {
                                            mediaPlayer = MediaPlayer.create(getContext(), R.raw.finish);
                                            mediaPlayer.start();
                                            statu = 0;
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    if (totalSize > finishSize) {
                                        if (mQmuiFullScreenPopup != null) {
                                            mQmuiFullScreenPopup.dismiss();
                                        }
                                        final Timer t = new Timer();
                                        t.schedule(new TimerTask() {
                                            public void run() {
                                                showResult.setVisibility(View.GONE); //todo
                                                t.cancel();
                                            }
                                        }, 1000);
                                    }

                                    if (totalSize <= finishSize && param.getProduct_code().equals(param.getLast_product_code())) { //todo
                                        if (mQmuiFullScreenPopup != null) {
                                            mQmuiFullScreenPopup.dismiss();
                                        }
                                        Log.d(TAG, "testFinish: " + totalSize);
                                        Log.d(TAG, "testFinish: " + finishSize);
                                        Log.d(TAG, "testFinish: 到此一游");
                                        Log.d(TAG, "testFinish1: " + showResult.getVisibility());

                                        try {
                                            Thread.sleep(200);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        showResult.setBackgroundColor(Color.YELLOW);
                                        showResult.setTextSize(70);
                                        showResult.setText("上料结束");

                                        Log.d(TAG, "testFinish2: " + showResult.getVisibility());
                                        try {
                                            Thread.sleep(200);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle("请确认结束上料")
                                                .setIcon(android.R.drawable.ic_dialog_info)
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        Log.d(TAG, "onClick");
                                                        startFragment(new UserFragment());
                                                    }
                                                }).show();
                                        Log.e(TAG, "AlertDialog");
                                        dialog.setCanceledOnTouchOutside(false);
                                        stopTimerTask();
                                        finishPositonRecord(pcbTaskCode, deviceCode);
                                        Log.d(TAG, "testFinish: stopTimerTask");
                                    }
                                }
                            }
                        }
                    }
                });
    }

    private void queryByReplaceProductCode(String replaceProductCode) {
        Kalle
                .get(obtainIP() + "base/deviceProductReplaceElement/queryByReplaceProductCode/" + replaceProductCode)
                //.body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<DeviceProductReplaceElementEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<DeviceProductReplaceElementEntity, String> response) {
                        //Log.d(TAG, "scanProductCode: test" + response);
                        if (mAdapter != null && response.isSucceed()) {
                            if (!(response.succeed() instanceof DeviceProductReplaceElementEntity)) {
                                Log.d(TAG, "onResponse: 不是ElementEntity类型" + response.succeed());
                                return;
                            }
                            deviceProductReplaceElementEntity = response.succeed();
                            //String code = deviceProductReplaceElementEntity.getOriginal_product_code();
                        }
                        Log.d(TAG, "scanProductCode: test " + response);

                    }
                });
    }


    private void queryDetailByProductCode(String productCode) {

        Kalle
                .get(obtainIP() + "PcbTaskPositionRecord/getDetailByProductCode/" + productCode)
                //.body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<PcbTaskPositionRecordDetailEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbTaskPositionRecordDetailEntity, String> response) {
                        //Log.d(TAG, "scanProductCode: test" + response);
                        if (mAdapter != null && response.isSucceed()) {
                            if (!(response.succeed() instanceof PcbTaskPositionRecordDetailEntity)) {
                                Log.d(TAG, "onResponse: 不是DetailEntity类型" + response.succeed());
                                return;
                            }
                            pcbTaskPositionRecordDetailEntity = response.succeed();
                            //String code = deviceProductReplaceElementEntity.getOriginal_product_code();
                        }
                        Log.d(TAG, "scanProductCode: test " + response);
                    }
                });
    }

    /**
     * 下料
     * @param productCode 扫描的物料编号
     */
    private void downPositionRecordDetail(String productCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("productCode", productCode);
            Log.d(TAG, "scanProductCode: test " + productCode);

        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }
        Kalle
                .post(obtainIP() + "/PcbTaskPositionRecord/downPositionRecordDetail")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<PcbTaskPositionRecordDetailEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<PcbTaskPositionRecordDetailEntity, String> response) {
                        //Log.d(TAG, "scanProductCode: test" + response);
                        if (mAdapter != null && response.isSucceed()) {
                            if (!(response.succeed() instanceof PcbTaskPositionRecordDetailEntity)) {
                                Log.d(TAG, "onResponse: 不是PcbTaskPositionRecordDetailEntity类型" + response.succeed());
                                return;
                            }
                            pcbTaskPositionRecordDetailEntity = response.succeed();
                        }
                        Log.d(TAG, "scanProductCode: test " + response);
                    }
                });
    }


    /*private void queryByProductCode(String productCode) {
        Kalle
                .get(obtainIP() + "base/deviceProductReplaceElement/queryByProductCode" + productCode)
                //.body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<DeviceProductReplaceElementEntity>() {
                    @Override
                    public void onResponse(SimpleResponse<DeviceProductReplaceElementEntity, String> response) {
                        //Log.d(TAG, "scanProductCode: test" + response);
                        if (mAdapter != null && response.isSucceed()) {
                            if (!(response.succeed() instanceof DeviceProductReplaceElementEntity)) {
                                Log.d(TAG, "onResponse: 不是ElementEntity类型" + response.succeed());
                                return;
                            }
                            deviceProductReplaceElementEntity = response.succeed();
                        }
                        Log.d(TAG, "scanProductCode: test " + response);

                    }
                });
    }*/

    /**
     * 全屏浮层次 带关闭按钮
     * 弹框设置了自动关闭时间 这里不进行手动关闭
     */
    private void fullScreenPopupWindow(View v, PcbTaskPositionRecordDetail detail) {
        QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();
        QMUIFrameLayout frameLayout = new QMUIFrameLayout(getContext());
        frameLayout.setBackground(
                QMUIResHelper.getAttrDrawable(getContext(), R.attr.qmui_skin_support_popup_bg));
        frameLayout.setBackgroundColor(detail == null ? Color.RED : Color.GREEN);
        builder.background(R.attr.qmui_skin_support_popup_bg);
        QMUISkinHelper.setSkinValue(frameLayout, builder);
        frameLayout.setRadius(QMUIDisplayHelper.dp2px(getContext(), 20));//60
        int padding = QMUIDisplayHelper.dp2px(getContext(), 0);//20
        frameLayout.setPadding(padding, padding, padding, padding);

        showResult = new TextView(getContext());
        showResult.setLineSpacing(QMUIDisplayHelper.dp2px(getContext(), 4), 1.0f);//4
        showResult.setPadding(padding, padding, padding, padding);
        if (detail == null) {
            Log.d(TAG, "testFinish: ---------------------------------- ");
            Log.d(TAG, "testFinish: " + showResult.getVisibility());
            showResult.setBackgroundColor(Color.RED);
            showResult.setTextSize(50);
            //showResult.setText("请扫描替代料...");
            showResult.setText("物料不在该程序中");
            Log.d(TAG, "testFinish: " + showResult.getVisibility());
        } else if (detail.getInstall_status().equals("2") && detail.getProduct_code().equals(detail.getLast_product_code())) { //todo
            showResult.setBackgroundColor(Color.YELLOW);
            showResult.setTextSize(60);
            showResult.setText("上料结束");
            stopTimerTask();
        } else {
            showResult.setBackgroundColor(Color.GREEN);
            //showResult.setTextColor(Color.WHITE);
            showResult.setTextSize(52);
            showResult.setText("上料中\n" + detail.getPosition());
        }
        builder.clear();
        builder.textColor(R.attr.app_skin_common_title_text_color);
        QMUISkinHelper.setSkinValue(showResult, builder);
        showResult.setGravity(Gravity.CENTER);

        builder.release();

        int size = QMUIDisplayHelper.dp2px(getContext(), 200);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(size, size);
        frameLayout.addView(showResult, lp);

        mQmuiFullScreenPopup = QMUIPopups.fullScreenPopup(getContext())
                .addView(frameLayout)
                .closeBtn(false) //弹框下面不带X按钮 todo
                .skinManager(QMUISkinManager.defaultInstance(getContext()))
                .onBlankClick(new QMUIFullScreenPopup.OnBlankClickListener() {
                    @Override
                    public void onBlankClick(QMUIFullScreenPopup popup) {
                        isPopUpShow = false;
                        stopTimerTask();
                    }
                })
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        isPopUpShow = false;
                        stopTimerTask();
                    }
                });
        mQmuiFullScreenPopup.show(v);

        isPopUpShow = true;
    }


    /**
     * 结束上料
     */
    private void finishPositonRecord(String pcbTaskCode, String deviceCode) {
        JSONObject object = null;
        try {
            object = new JSONObject();
            object.put("processTaskCode", pcbTaskCode);
            object.put("deviceCode", deviceCode);
        } catch (JSONException e) {
            object = null;
        }

        if (object == null) {
            return;
        }

        Kalle
                .post(obtainIP() + "PcbTaskPositionRecord/finishPositionRecord")
                .body(new JsonBody(object.toString()))
                .converter(new JsonConverter())
                .tag(this)
                .perform(new SimpleCallback<String>() {
                    @Override
                    public void onResponse(SimpleResponse<String, String> response) {
                        Log.d(TAG, "结束上料: " + response.succeed());

                        if (response.isSucceed()) {
                            ToastUtil.showToast(getActivity(), response.succeed());
                        } else {
                            ToastUtil.showToast(getActivity(), response.failed());
                        }
                    }

                });
    }
}
//                                    if(productCode.equals(param.getLast_product_code())){
//                                        //queryByReplaceProductCode(param.getProduct_code());
//                                        //需要一个接口通过上面拿到的物料编号查询这条数据的详细信息,把查询到的detail赋值给param todo
//                                        //queryDetailByProductCode(param.getProduct_code());
//                                        fullScreenPopupWindow(LoadFragment.this.getView(), param);
//                                        Log.d(TAG, "scanProductCode: test productCode 扫描的物料码" + productCode);
//                                        Log.d(TAG, "scanProductCode: test product_code detail的物料码" + param.getProduct_code());
//                                        Log.d(TAG, "scanProductCode: test last_product_code detail的替代料码" + param.getLast_product_code());
//                                    } else {
//                                        fullScreenPopupWindow(LoadFragment.this.getView(), param);
//                                    }

//                                    if ("2".equals(response.succeed().getStatus())) {
//                                        int pos = mAdapter.getData().indexOf(param);
//                                        PcbTaskPositionRecordDetail find = mAdapter.getItem(pos);
//                                        find.setInstall_status("2");
//                                        finishSize++;
//                                        Log.d(TAG, "testFinish2: total" + totalSize);
//                                        Log.d(TAG, "testFinish2: finish" + finishSize);
//                                        mAdapter.notifyDataSetChanged();
//                                        try {
//                                            if (statu == 1) {
//                                                mediaPlayer = MediaPlayer.create(getContext(), R.raw.finish);
//                                                mediaPlayer.start();
//                                                statu = 0;
//                                            }
//
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//
//                                    }

//dlg.setOnKeyListener(new Dialog.OnKeyListener() {
//@Override
//public boolean onKey(DialogInterface arg0, int keyCode,
//        KeyEvent event) {
//        if (event.getAction() != KeyEvent.ACTION_DOWN)
//        return true;
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//        new AlertDialog.Builder(getContext())
//        .setIcon(android.R.drawable.ic_dialog_alert)
//        .setTitle("退出")
//        .setMessage("确认完成?")
//        .setPositiveButton("是", new DialogInterface.OnClickListener() {
//@Override
//public void onClick(DialogInterface dialog, int which) {
//        dialog.cancel();
//        dlg.dismiss();
//        }
//        }).setNegativeButton("No", null).show();
//        Log.e("Key","back");
//        }
//        return false;
//        }
//        });
